package com.fy.controller;

import com.fy.common.annotation.GlobalInterceptor;
import com.fy.pojo.dto.activity.ActiveListQueryDTO;
import com.fy.pojo.dto.activity.ActivityDTO;
import com.fy.pojo.dto.activity.AddActivityDTO;
import com.fy.pojo.dto.activity.UpdateActivityDTO;
import com.fy.pojo.dto.admin.AdminLoadUserListDTO;
import com.fy.pojo.dto.admin.AdminSysDTO;
import com.fy.pojo.dto.announcement.AddAnnouncementDTO;
import com.fy.pojo.dto.announcement.AnnouncementDTO;
import com.fy.pojo.dto.announcement.AnnouncementQueryDTO;
import com.fy.pojo.dto.announcement.UpdateAnnouncementDTO;
import com.fy.pojo.dto.file.FileQueryDTO;
import com.fy.pojo.entity.AdminSys;
import com.fy.pojo.vo.activity.ActivityStatisticsVO;
import com.fy.pojo.vo.admin.AdminSysVO;
import com.fy.pojo.vo.file.FoloderVO;
import com.fy.service.*;
import com.fy.utils.fileUtils.FileUploadTool;
import com.fy.utils.result.PageResult;
import com.fy.utils.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private FileUploadTool fileUploadTool;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 获取系统设置
     *
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/getSysSettings")
    public Result getSysSettings() {
        AdminSysVO adminSysVO = adminService.getSysSettings();
        return Result.success(adminSysVO);
    }

    /**
     * 保存系统设置
     *
     * @param adminSysDTO
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/saveSysSettings")
    public Result saveSysSettings(AdminSysDTO adminSysDTO) {
        log.info("adminSysDTO:{}", adminSysDTO);
        AdminSys adminSys = new AdminSys();
        adminSys.setUserInitUseSpace(adminSysDTO.getUserInitUseSpace());
        adminSys.setEmCodeOutTime(Integer.valueOf(adminSysDTO.getRegisterEmailTitle()));
        adminSys.setPicCodeOutTime(Integer.valueOf(adminSysDTO.getRegisterEmailContent()));
        log.info("保存系统设置结果:{}", adminSysDTO);
        adminService.saveSysSettings(adminSys);
        return Result.success();
    }

    /**
     * 获取用户列表
     *
     * @param adminLoadUserListDTO
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/loadUserList")
    public Result loadUserList(AdminLoadUserListDTO adminLoadUserListDTO) {
        PageResult pageResult = userService.loadUserList(adminLoadUserListDTO);
        return Result.success(pageResult);
    }

    // todo
    @PostMapping("/user/list")
    public Result<Map<String, Object>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String userType) {

        log.info("pageNum:{},pageSize:{},keyword:{},status:{},userType:{}", pageNum, pageSize, keyword, status,
                userType);
        // 模拟用户数据
        List<Map<String, Object>> userList = new ArrayList<>();

        // 虚拟用户数据
        userList.add(createUser("1", "张三", "zhangsan@example.com", "1", "1", 5, 10, "2024-03-20 10:30:00"));
        userList.add(createUser("2", "李四", "lisi@example.com", "0", "0", 8, 10, "2024-03-19 15:45:00"));
        userList.add(createUser("3", "王五", "wangwu@example.com", "1", "1", 15, 20, "2024-03-20 09:15:00"));
        userList.add(createUser("4", "赵六", "zhaoliu@example.com", "1", "0", 3, 10, "2024-03-18 16:20:00"));
        userList.add(createUser("5", "钱七", "qianqi@example.com", "1", "1", 25, 50, "2024-03-20 11:00:00"));

        // 统计数据
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalUsers", 5);
        stats.put("activeUsers", 4);
        stats.put("vipUsers", 3);
        stats.put("totalStorage", 100); // 总存储空间，单位GB

        // 返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("list", userList);
        data.put("total", userList.size());
        data.put("stats", stats);

        return Result.success(data);
    }

    private Map<String, Object> createUser(String userId, String nickName, String email,
            String status, String userType, int useSpace, int totalSpace, String lastLoginTime) {
        Map<String, Object> user = new HashMap<>();
        user.put("userId", userId);
        user.put("nickName", nickName);
        user.put("email", email);
        user.put("status", status); // 1:正常, 0:禁用
        user.put("userType", userType); // 1:VIP用户, 0:普通用户
        user.put("useSpace", useSpace); // 已使用空间，单位GB
        user.put("totalSpace", totalSpace); // 总空间，单位GB
        user.put("lastLoginTime", lastLoginTime);
        user.put("avatar", "https://fypan.oss-cn-hangzhou.aliyuncs.com/3499802689.JPG"); // 默认头像
        return user;
    }

    /**
     * 获取文件夹信息
     *
     * @param fileId
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/getFolderInfo")
    public Result getFolderInfo(@RequestParam("path") String fileId) {
        log.info("fileId:{}", fileId);
        List<FoloderVO> foloderVO = fileInfoService.getFoloderInfo(fileId);
        return Result.success(foloderVO);
    }

    /**
     * 获取用户文件列表
     *
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/loadFileList")
    public Result loadFileList(FileQueryDTO fileQueryDTO) {
        log.info("fileQueryDTO:{}", fileQueryDTO);
        PageResult pageResult = adminService.loadFileList(fileQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 管理员启用禁用用户账户
     *
     * @param userId
     * @param status
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/updateUserStatus")
    public Result updateUserStatus(String userId, String status) {
        adminService.updateUserStatus(userId, status);
        return Result.success();
    }

    /**
     * 分配空间
     *
     * @param nickName
     * @param changeSpace
     * @param totalSpace
     * @param useSpace
     * @return
     */

    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/updateUserSpace")
    public Result updateUserSpace(String nickName, long changeSpace, long totalSpace,
            long useSpace) {
        adminService.updateUserSpace(nickName, totalSpace, useSpace, changeSpace);
        return Result.success();
    }

    /**
     * 删除文件
     *
     * @param fileIdList
     * @return
     */
    @GlobalInterceptor(checkParams = true, checkAdmin = true)
    @PostMapping("/delFile")
    public Result delFile(@RequestParam("fileIdAndUserIds") List<String> fileIdList) {
        log.info("批量删除文件id接收:{}", fileIdList);
        adminService.delFile(fileIdList);
        return Result.success();
    }

    /**
     * 发布活动
     */
    @PostMapping("/activity/publish")
    @GlobalInterceptor(checkAdmin = true)
    public Result publishActivity(ActivityDTO activityDTO) {
        return activityService.publishActivity(activityDTO);
    }

    /**
     * 获取活动列表
     *
     * @param activeListQueryDTO
     * @return
     */
    @PostMapping("/activity/list")
    @GlobalInterceptor(checkAdmin = true)
    public Result getActivityList(ActiveListQueryDTO activeListQueryDTO) {
        log.info("activeListQueryDTO:{}", activeListQueryDTO);
        return activityService.getActivityList(activeListQueryDTO);
    }

    /**
     * 获取活动公告列表
     *
     * @param announcementQueryDTO
     * @return
     */
    @PostMapping("/announcement/list")
    @GlobalInterceptor(checkAdmin = true)
    public Result getAnnouncementList(AnnouncementQueryDTO announcementQueryDTO) {
        return announcementService.getAnnouncementList(announcementQueryDTO);
    }

    /**
     * 获取活动统计数据
     */
    @PostMapping("/activity/statistics")
    public Result<ActivityStatisticsVO> getStatistics() {
        return Result.success(activityService.getStatistics());
    }

    @PostMapping("/activity/uploadCoverFile")
    @GlobalInterceptor(checkAdmin = true)
    public Result<String> uploadCoverFile(@RequestParam("file") MultipartFile file,@RequestParam("id") int id) {
        return Result.success(activityService.uploadCoverFile(id,file));
    }

    // 发布公告：http://localhost:1024/api/admin/announcement/publish
    @PostMapping("/announcement/publish")
    @GlobalInterceptor(checkAdmin = true)
    public Result publishAnnouncement(AnnouncementDTO announcementDTO) {
        return Result.success(announcementService.publishAnnouncement(announcementDTO));
    }

    /**
     * 更新活动
     */
    @PostMapping("/activity/update")
    @GlobalInterceptor(checkAdmin = true)
    public Result updateActivity(UpdateActivityDTO updateActivityDTO) {
        return activityService.updateActivity(updateActivityDTO);
    }

    /**
     * 删除活动
     */
    @PostMapping("/activity/delete/{id}")
    @GlobalInterceptor(checkAdmin = true)
    public Result deleteActivity(@PathVariable("id") Long id) {
        return Result.success(activityService.removeById(id));
    }

    /**
     * 删除公告
     */
    @PostMapping("/announcement/delete/{id}")
    @GlobalInterceptor(checkAdmin = true)
    public Result deleteAnnouncement(@PathVariable("id") Long id) {
        boolean remove = announcementService.removeById(id);
        return Result.success(remove);
    }

    /**
     * 更新公告
     */
    @PostMapping("/announcement/update")
    @GlobalInterceptor(checkAdmin = true)
    public Result updateAnnouncement(UpdateAnnouncementDTO updateAnnouncementDTO) {
        return announcementService.updateAnnouncement(updateAnnouncementDTO);
    }

    /**
     * 添加活动
     */
    @PostMapping("/activity/add")
    @GlobalInterceptor(checkAdmin = true)
    public Result addActivity(AddActivityDTO addActivityDTO) {
        log.info("添加活动，参数:{}", addActivityDTO);
        return activityService.addActivity(addActivityDTO);
    }

    /**
     * 添加公告
     */
    @PostMapping("/announcement/add")
    @GlobalInterceptor(checkAdmin = true)
    public Result addAnnouncement(AddAnnouncementDTO addAnnouncementDTO) {
        log.info("添加公告，参数:{}", addAnnouncementDTO);
        return announcementService.addAnnouncement(addAnnouncementDTO);
    }
}
